#pragma once
#include <middleware/mk_lib/mk_auto_mutex.h>
#include "gm_sc_app_mgr.h"
#include "gm_sc_digest_mgr.h"

class gm_sc_dev : public gm_handle
{
public:
	gm_sc_dev(void);
	gm_sc_dev(char *name);
	gm_sc_dev(char *name, HANDLE handle);

	virtual ~gm_sc_dev(void);

public:
	char* Name() { return _name; }
	void Name(char *val) { strncpy(_name, val, 32); }

	gm_sc_app_mgr* get_app_mgr() { return &_sc_app_mgr; }

	HANDLE get_apdu_handle() const { return _apdu_handle; }

	int  IsConnected() const { return _bconnected==1?1:0; }
	void  IsConnected(int val) { _bconnected = val; }

	int IsAuth() const { return _bauth; }
	void IsAuth(int val) { _bauth = val; }

	int lock_dev(ULONG ulTimeOut);
	int unlock_dev();

	int begin_transaction();
	int end_transaction();

	gm_handle_mgr *get_digest_mgr(){return &sc_digest;}

	gm_sc_app * find_app(HAPPLICATION hApplication);

	gm_sc_app * find_app_by_name(char * appName);

	gm_sc_digest * find_digest( HANDLE hDigest);

	gm_sc_key * find_key( HANDLE hKey, gm_sc_app *& pApp, gm_sc_cont *& pContainer);

	gm_sc_mac * find_mac( HANDLE hMac, gm_sc_app *& pApp, gm_sc_cont *& pContainer);

	gm_sc_cont * find_container(HCONTAINER hContainer, gm_sc_app *& pApp); 

	gm_sc_app * create_app(AppInfoRsp appinfo, LPSTR appName);

	ULONG		remove_app(gm_sc_app * pApp);
	
	ULONG		remove_app(LPSTR appName);

	gm_sc_digest * create_digest(ULONG ulAlgId);

	ULONG		remove_digest(gm_sc_digest *pDigest);

	gm_sc_key * get_first_key(gm_sc_app *&pApp, gm_sc_cont *&pContainer);

	ULONG		get_interface_type();

	HANDLE		get_dev_os_handle();

	ULONG		get_dev_os_path(char devPath[260]);

public:
	ULONG		connect();

	ULONG		connect(char * devPath, HANDLE hCard);
	
	ULONG		disconnect();
	
	ULONG		get_max_apdu_len() {return _max_apdu_len; }

	ULONG		get_max_hs_data_len() { return _max_hs_data_len;}

	BOOL		if_support_hs();

private:

	char		_name[256];
	HANDLE		_device_handle;
	HANDLE		_apdu_handle;
	int			_bauth;
	int			_bconnected;
	ULONG		_AuthAlgId;

	ULONG			_max_apdu_len;
	ULONG			_max_hs_data_len ;

	mk_mutex	_mutex;
	gm_sc_app_mgr _sc_app_mgr;

	gm_handle_mgr  sc_digest;
};
